<?php
session_start();
if($_SESSION['user']=="") {
    ?>
    <script>
        alert('当前未登录！');
        window.location.href='../login.html';
    </script>
<?php
}
//连接数据库
try {
    function success(){
        $result=[
            'error' => 0,
            'message' => '成功'
        ];
        return json_encode($result);
    }
    function error($mag){
        $data = [
            'error' => 1,
            'message' => $mag
        ];
        return json_encode($data);
    }

    //文件上传
    if(!isset($_FILES['roomImg'])){
        die('无文件上传');
    };
    if($_FILES['roomImg']['error'] != 0){
        die('无文件上传');
    };
    $allow=[
        'image/.jpeg',
        'image/.png',
        'image/.gif'
    ];
    if(in_array($_FILES['roomImg']['type'],$allow)){
        die('禁止上传该类型！');
    };
    $file_name=$_FILES['roomImg']['name'];
    $file_name=explode('.',$file_name)[1];
    $file_name=$_POST['roomId'].'.'.$file_name;
    $file_name='../image/'.$file_name;
    move_uploaded_file($_FILES['roomImg']['tmp_name'],$file_name);

    //连接数据库
    $db = new PDO('mysql:dbname=liaotian;host=106.14.7.147', 'root', '123456');
    $search = $db->prepare('select * from room where roomId=:roomId');
    $search->execute([
        ':roomId'=> $_POST['roomId']
    ]);
    $reSearch=$search->fetch();
    if($_POST['roomId'] ==$reSearch['roomId']){
        die(error('房间号码已存在'));
    }
    $add= $db->prepare('insert into room (username,roomName,roomId,roomNum,roomImg,newDate) 
                        values(:username,:roomName,:roomId,:roomNum,:roomImg,:newDate)');
    $data[':username']=$_SESSION['user'];
    $data[':roomName']=$_POST['roomName'];
    $data[':roomId']=$_POST['roomId'];
    $data[':roomNum']=$_POST['roomNum'];
    $data[':roomImg']=$file_name;
    $data[':newDate']=date('y-m-d');

    if($add->execute($data) === false){
        print_r($add->errorInfo());
    }
    $re=$add->fetch();
    if(empty($_POST['roomName'])){
        die(error('房间名称不能为空'));
    };
    if(empty($_POST['roomId'])){
        die(error('房间号码不能为空'));
    }
    if(empty($_POST['roomNum'])){
        die(error('房间人数不能为空'));
    }

    if(empty($_FILES['roomImg'])){
        die(error('头像不能为空'));
    }
    echo success();
} catch (PDOException $e) {
    echo 'Connection failed';
}
